<!--
 * @Author: Li Zengkun
 * @Date: 2022-07-26 09:35:50
 * @LastEditors: Li Zengkun
 * @LastEditTime: 2022-08-15 20:15:10
 * @Description: 添加地址
-->

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="stylesheet" href="../css/reset.css">
    <link rel="stylesheet" href="../css/style.css">
    <link rel="stylesheet" href="../css/edit_add_address.css">
    <link rel="stylesheet" href="../node_modules/font-awesome/css/font-awesome.min.css">
    <script src="../node_modules/jquery/dist/jquery.min.js"></script>
    <script src="../node_modules/distpicker/dist/distpicker.min.js"></script>
    <title>添加地址</title>
</head>

<body>
    <header>
        <a id="return" href="javascript:history.back()">
            <i class="fa fa-chevron-left" aria-hidden="true"></i>
        </a>
        添加地址
        <p></p>
    </header>

    <form action="#" class="content">
        <label class="item" for="consignee">
            <span> 收货人：</span>
             <input placeholder="请输入收货人姓名" type="text" id="consignee" name="consignee" >
         </label>
        <label for="phonenum">
            <span> 手机号码：</span>
             <input placeholder="请输入收货人手机号码" type="number" id="phonenum" name="phonenum" >
         </label>
        <label for="address">
            <span> 所在地区：</span>
             <div id="address-checkgroup">
                <select id="province-select">
                    <option value="">省/直辖市/自治区</option>
                </select>
                <select id="city-select">
                    <option value="">市/自治州</option>
                </select>
                <select id="county-select">
                    <option value="">区/县/市</option>
                </select>
                <select id="town-select">
                    <option value="">街道/镇</option>
                </select>
              </div>
         </label>
        <label for="address-details">
            <span> 详细地址：</span>
             <textarea placeholder="门派，楼层等" name="address-details" id="address-details"  rows="3"></textarea> 
         </label>
        <label for="post-code">
            <span> 邮政编码：</span>
             <input placeholder="请输入邮政编码" type="number" id="post-code" name="post-code" >
         </label>
        <label for="default-address">
            <span> 默认地址：</span>
             <input type="checkbox" id="default-address" name="default-address" >
         </label>

        <!-- <input class="save pointer" value="添加地址"> -->

    </form>

    <div id="add-address-btn" class="bottom-btn">
        添加地址
    </div>

    <!-- 提示 tip -->
    <span id="tip" class="tip"></span>
</body>


<script src="../js/axios.min.js"></script>
<script src="../js/axios_config.js"></script>
<script>
    let oProvinceSelect = document.querySelector('#province-select')
    let oCitySelect = document.querySelector('#city-select')
    let oCountySelect = document.querySelector('#county-select')
    let oTownSelect = document.querySelector('#town-select')
    let oName = document.querySelector('#consignee')
    let oPhone = document.querySelector('#phonenum')
    let oAddressDetail = document.querySelector('#address-details')
    let oPostCode = document.querySelector('#post-code')
    let oIsDefault = document.querySelector('#default-address')
    let oAddAddressBtn = document.querySelector('#add-address-btn')
    let oTip = document.querySelector('#tip')

    let province = null

    init()

    /**
     * @description: 初始化
     * @return {*}
     */
    async function init() {
        province = await getProvince()
        console.log(province);
        await initSelect(oProvinceSelect, province, 1)

        // 省 选择器
        oProvinceSelect.addEventListener('change', async() => {
            let city = await getCity(parseInt(oProvinceSelect.value))
            console.log(city);
            initSelect(oCitySelect, city, 2)
        })

        // 市 选择器
        oCitySelect.addEventListener('change', async() => {
            let county = await getCounty(parseInt(oCitySelect.value))
            console.log(county);
            initSelect(oCountySelect, county, 3)
        })

        // 县区 选择器
        oCountySelect.addEventListener('change', async() => {
            let town = await getTown(parseInt(oCountySelect.value))
            console.log(town);
            initSelect(oTownSelect, town, 4)
        })

        // 添加地址事件
        oAddAddressBtn.addEventListener('click', async() => {
            let name = oName.value;
            let tel = oPhone.value;
            let province_id = oProvinceSelect.value;
            let city_id = oCitySelect.value;
            let county_id = oCountySelect.value;
            let town_id = oTownSelect.value;
            let street = oAddressDetail.value;
            let code = oPostCode.value;
            let isDefault = oIsDefault.checked ? 1 : 0;
            if (!name || !tel || !province_id || !city_id ||
                !county_id || !town_id || !street || !code) {
                openTip("请填写完整")
                return
            } else {
                let res = await addAddress(name, tel, province_id, city_id, county_id, town_id, street, code, isDefault);
                if (res) {
                    openTip('添加成功,3秒后自动返回地址列表')
                    setTimeout(() => {
                        location.href = './shipping_address.html'
                    }, 3000)
                } else {
                    openTip('添加失败')
                }
            }
        })
    }


    /**
     * @description: 弹出提示框
     * @return {*}
     * @param {*} text (String) 提示内容
     */
    function openTip(text) {
        oTip.style.display = 'inline-block'
        oTip.innerText = text
        setTimeout(() => {
            oTip.style.display = 'none'
        }, 3000)
    }

    /**
     * @description:  添加收货地址
     * @return {*}
     * @param {*} name (String)         收货人姓名
     * @param {*} tel (Number)          电话
     * @param {*} province_id  (Number) 省份id
     * @param {*} city_id (Number)      城市id
     * @param {*} county_id  (Number)   县区id
     * @param {*} town_id (Number)      街道（镇）id
     * @param {*} street (String)       详细地址
     * @param {*} code (String)         邮编
     * @param {*} isDefault (Number)    是否默认（1为默认；0不默认）
     */
    async function addAddress(name, tel, province_id, city_id, county_id, town_id, street, code, isDefault) {
        let result = false
        await axios.post('/address/add', {
            name: name,
            tel: tel,
            province_id: province_id,
            city_id: city_id,
            county_id: county_id,
            town_id: town_id,
            street: street,
            code: code,
            isDefault: isDefault
        }).then(resp => {
            result = resp.status
        })
        return result
    }

    /**
     * @description: 更新地区选择器
     * @return {*}
     * @param {*} select (Object) 选择器 Dom 对象
     * @param {*} options (Array) 地区列表数组
     * @param {*} level (Number) 等级
     */
    async function initSelect(select, options, level) {
        if (level === 1) {
            while (oProvinceSelect.querySelector('option')) {
                oProvinceSelect.querySelector('option').remove()
            }
            while (oCitySelect.querySelector('option')) {
                oCitySelect.querySelector('option').remove()
            }
            while (oCountySelect.querySelector('option')) {
                oCountySelect.querySelector('option').remove()
            }
            while (oTownSelect.querySelector('option')) {
                oTownSelect.querySelector('option').remove()
            }
            oProvinceSelect.insertAdjacentHTML('beforeend', `<option value="">省/直辖市/自治区</option>`)
            oCitySelect.insertAdjacentHTML('beforeend', `<option value="">市/自治州</option>`)
            oCountySelect.insertAdjacentHTML('beforeend', `<option value="">区/县/市</option>`)
            oTownSelect.insertAdjacentHTML('beforeend', `<option value="">街道/镇</option>`)
            options.forEach(item => {
                let optionHTML = `<option value="${item.province_id}">${item.name}</option>`
                select.insertAdjacentHTML('beforeend', optionHTML)
            });

        }
        if (level === 2) {
            while (oCitySelect.querySelector('option')) {
                oCitySelect.querySelector('option').remove()
            }
            while (oCountySelect.querySelector('option')) {
                oCountySelect.querySelector('option').remove()
            }
            while (oTownSelect.querySelector('option')) {
                oTownSelect.querySelector('option').remove()
            }
            oCitySelect.insertAdjacentHTML('beforeend', `<option value="">市/自治州</option>`)
            oCountySelect.insertAdjacentHTML('beforeend', `<option value="">区/县/市</option>`)
            oTownSelect.insertAdjacentHTML('beforeend', `<option value="">街道/镇</option>`)
            options.forEach(item => {
                let optionHTML = `<option value="${item.city_id}">${item.name}</option>`
                select.insertAdjacentHTML('beforeend', optionHTML)
            });
        }
        if (level === 3) {
            while (oCountySelect.querySelector('option')) {
                oCountySelect.querySelector('option').remove()
            }
            while (oTownSelect.querySelector('option')) {
                oTownSelect.querySelector('option').remove()
            }
            oCountySelect.insertAdjacentHTML('beforeend', `<option value="">区/县/市</option>`)
            oTownSelect.insertAdjacentHTML('beforeend', `<option value="">街道/镇</option>`)
            options.forEach(item => {
                let optionHTML = `<option value="${item.county_id}">${item.name}</option>`
                select.insertAdjacentHTML('beforeend', optionHTML)
            });
        }
        if (level === 4) {
            while (oTownSelect.querySelector('option')) {
                oTownSelect.querySelector('option').remove()
            }
            oTownSelect.insertAdjacentHTML('beforeend', `<option value="">街道/镇</option>`)
            options.forEach(item => {
                let optionHTML = `<option value="${item.town_id}">${item.name}</option>`
                select.insertAdjacentHTML('beforeend', optionHTML)
            });
        }
    }

    /**
     * @description: 获取所有省份
     * @return {*} result(Array) 省份对象数组
     */
    async function getProvince() {
        let result = null
        await axios.get('/pcct/province').then(resp => {
            if (resp.status) {
                result = resp.data
            }
        })
        return result
    }

    /**
     * @description: 根据 省份id 选择城市 
     * @return {*} result(Array) 城市对象数组
     */
    async function getCity(id) {
        let result = null
        await axios.get('/pcct/city', {
            params: {
                id: parseInt(id)
            }
        }).then(resp => {
            if (resp.status) {
                result = resp.data
            }
        })
        return result
    }

    /**
     * @description: 根据 城市id 选择 县区 
     * @return {*} result(Array) 县区对象数组
     */
    async function getCounty(id) {
        let result = null
        await axios.get('/pcct/county', {
            params: {
                id: parseInt(id)
            }
        }).then(resp => {
            if (resp.status) {
                result = resp.data
            }
        })
        return result
    }

    /**
     * @description: 根据 县区id 选择 城镇
     * @return {*} result(Array) 城镇 对象数组
     */
    async function getTown(id) {
        let result = null
        await axios.get('/pcct/town', {
            params: {
                id: parseInt(id)
            }
        }).then(resp => {
            if (resp.status) {
                result = resp.data
            }
        })
        return result
    }
</script>



</html>